package CarRental;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class AdminFrame extends JFrame {
    private JTable table;
    private DefaultTableModel tableModel;

    public AdminFrame() {
        setTitle("管理员界面"); // 设置窗口标题
        setSize(800, 600); // 设置窗口大小
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // 设置关闭操作
        setLocationRelativeTo(null); // 窗口居中显示

        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout()); // 设置面板布局为BorderLayout

        // 创建按钮面板
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new GridLayout(1, 8)); // 设置按钮面板布局为1行8列的GridLayout

        JButton viewVehiclesButton = new JButton("查看车辆信息");
        JButton addVehicleButton = new JButton("增加车辆信息");
        JButton modifyVehicleButton = new JButton("修改车辆信息");
        JButton deleteVehicleButton = new JButton("删除车辆信息");
        JButton viewOrdersButton = new JButton("查看订单信息");
        JButton viewRevenueButton = new JButton("查看营业额");
        JButton switchAccountButton = new JButton("切换账号"); // 新增切换账号按钮
        JButton exitButton = new JButton("退出程序"); // 新增退出按钮

        buttonPanel.add(viewVehiclesButton);
        buttonPanel.add(addVehicleButton);
        buttonPanel.add(modifyVehicleButton);
        buttonPanel.add(deleteVehicleButton);
        buttonPanel.add(viewOrdersButton);
        buttonPanel.add(viewRevenueButton);
        buttonPanel.add(switchAccountButton); // 添加切换账号按钮
        buttonPanel.add(exitButton); // 添加退出按钮

        // 创建表格
        tableModel = new DefaultTableModel();
        table = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(table);

        panel.add(buttonPanel, BorderLayout.NORTH); // 将按钮面板放置在窗口顶部
        panel.add(scrollPane, BorderLayout.CENTER); // 将表格放置在窗口中央

        // 绑定按钮事件
        viewVehiclesButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                viewVehicles(); // 查看车辆信息
            }
        });

        addVehicleButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                addVehicle(); // 增加车辆信息
            }
        });

        modifyVehicleButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                modifyVehicle(); // 修改车辆信息
            }
        });

        deleteVehicleButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                deleteVehicle(); // 删除车辆信息
            }
        });

        viewOrdersButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                viewOrders(); // 查看订单信息
            }
        });

        viewRevenueButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                viewRevenue(); // 查看营业额
            }
        });

        switchAccountButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose(); // 关闭当前窗口
                new LoginFrame().setVisible(true); // 返回登录界面
            }
        });

        exitButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0); // 退出程序
            }
        });

        add(panel); // 将面板添加到窗口中
    }

    // 查看车辆信息
    private void viewVehicles() {
        tableModel.setRowCount(0); // 清空表格
        tableModel.setColumnIdentifiers(new String[]{"VehicleID", "Type", "Brand", "Color", "Rent", "Status"});

        String sql = "SELECT * FROM Vehicles";
        try (Connection conn = DBConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {

            while (rs.next()) {
                int vehicleId = rs.getInt("VehicleID");
                String type = rs.getString("Type");
                String brand = rs.getString("Brand");
                String color = rs.getString("Color");
                int rent = rs.getInt("Rent");
                String status = rs.getString("Status");

                tableModel.addRow(new Object[]{vehicleId, type, brand, color, rent, status});
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "Error: " + e.getMessage());
        }
    }

    // 增加车辆信息
    private void addVehicle() {
        String type = JOptionPane.showInputDialog("请输入车辆类型 (Car, Bus, Truck):");
        while (!type.equals("Car") && !type.equals("Bus") && !type.equals("Truck")) {
            type = JOptionPane.showInputDialog("输入无效，请重新输入车辆类型 (Car, Bus, Truck):");
        }

        String brand = JOptionPane.showInputDialog("请输入车辆品牌:");
        String color = JOptionPane.showInputDialog("请输入车辆颜色:");
        int rent = Integer.parseInt(JOptionPane.showInputDialog("请输入租金:"));
        String status = JOptionPane.showInputDialog("请输入车辆状态 (Free, Rented):");

        String sql = "INSERT INTO Vehicles (Type, Brand, Color, Rent, Status) VALUES (?, ?, ?, ?, ?)";
        try (Connection conn = DBConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, type);
            pstmt.setString(2, brand);
            pstmt.setString(3, color);
            pstmt.setInt(4, rent);
            pstmt.setString(5, status);
            pstmt.executeUpdate();

            JOptionPane.showMessageDialog(this, "车辆信息添加成功！");
            viewVehicles(); // 刷新车辆信息表格
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "Error: " + e.getMessage());
        }
    }

    // 修改车辆信息
    private void modifyVehicle() {
        int vehicleId = Integer.parseInt(JOptionPane.showInputDialog("请输入要修改的车辆ID:"));
        String type = JOptionPane.showInputDialog("请输入新的车辆类型 (Car, Bus, Truck):");
        String brand = JOptionPane.showInputDialog("请输入新的车辆品牌:");
        String color = JOptionPane.showInputDialog("请输入新的车辆颜色:");
        int rent = Integer.parseInt(JOptionPane.showInputDialog("请输入新的租金:"));
        String status = JOptionPane.showInputDialog("请输入新的车辆状态 (Free, Rented):");

        String sql = "UPDATE Vehicles SET Type = ?, Brand = ?, Color = ?, Rent = ?, Status = ? WHERE VehicleID = ?";
        try (Connection conn = DBConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, type);
            pstmt.setString(2, brand);
            pstmt.setString(3, color);
            pstmt.setInt(4, rent);
            pstmt.setString(5, status);
            pstmt.setInt(6, vehicleId);
            int rowsAffected = pstmt.executeUpdate();

            if (rowsAffected > 0) {
                JOptionPane.showMessageDialog(this, "车辆信息修改成功！");
                viewVehicles(); // 刷新车辆信息表格
            } else {
                JOptionPane.showMessageDialog(this, "未找到车辆ID为 " + vehicleId + " 的车辆信息。");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "Error: " + e.getMessage());
        }
    }

    // 删除车辆信息
    private void deleteVehicle() {
        int vehicleId = Integer.parseInt(JOptionPane.showInputDialog("请输入要删除的车辆ID:"));

        String sql = "DELETE FROM Vehicles WHERE VehicleID = ?";
        try (Connection conn = DBConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, vehicleId);
            int rowsAffected = pstmt.executeUpdate();

            if (rowsAffected > 0) {
                JOptionPane.showMessageDialog(this, "车辆信息删除成功！");
                viewVehicles(); // 刷新车辆信息表格
            } else {
                JOptionPane.showMessageDialog(this, "未找到车辆ID为 " + vehicleId + " 的车辆信息。");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "Error: " + e.getMessage());
        }
    }

    // 查看订单信息
    private void viewOrders() {
        tableModel.setRowCount(0); // 清空表格
        tableModel.setColumnIdentifiers(new String[]{"OrderID", "UserID", "Username", "VehicleID", "RentDate", "ReturnDate", "TotalRent", "OrderStatus"});

        String sql = "SELECT Orders.OrderID, Orders.UserID, Users.Username, Orders.VehicleID, Orders.RentDate, Orders.ReturnDate, Orders.TotalRent, Orders.OrderStatus " +
                "FROM Orders " +
                "JOIN Users ON Orders.UserID = Users.UserID";
        try (Connection conn = DBConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {

            while (rs.next()) {
                int orderId = rs.getInt("OrderID");
                int userId = rs.getInt("UserID");
                String username = rs.getString("Username");
                int vehicleId = rs.getInt("VehicleID");
                String rentDate = rs.getString("RentDate");
                String returnDate = rs.getString("ReturnDate");
                int totalRent = rs.getInt("TotalRent");
                String orderStatus = rs.getString("OrderStatus");

                tableModel.addRow(new Object[]{orderId, userId, username, vehicleId, rentDate, returnDate, totalRent, orderStatus});
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "Error: " + e.getMessage());
        }
    }

    // 查看营业额
    private void viewRevenue() {
        tableModel.setRowCount(0); // 清空表格
        tableModel.setColumnIdentifiers(new String[]{"TotalRevenue"});

        String sql = "SELECT SUM(PaymentAmount) AS TotalRevenue FROM Payments";
        try (Connection conn = DBConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {

            if (rs.next()) {
                int totalRevenue = rs.getInt("TotalRevenue");
                tableModel.addRow(new Object[]{totalRevenue});
            } else {
                tableModel.addRow(new Object[]{"0"});
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "Error: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        new AdminFrame().setVisible(true); // 启动管理员界面
    }
}
